package cn.chiship.sdk.third.core.wx.util;

import cn.chiship.sdk.core.encryption.Sha1Util;
import cn.chiship.sdk.core.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lijian
 */
public class WxPubUtil {

	private WxPubUtil() {
	}

	/**
	 * 微信公众号验签
	 * @param token
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return 结果
	 * @throws NoSuchAlgorithmException
	 */
	public static boolean checkSignature(String token, String signature, String timestamp, String nonce)
			throws NoSuchAlgorithmException {
		String[] arrs = new String[] { token, timestamp, nonce };
		Arrays.sort(arrs);
		StringBuilder builder = new StringBuilder();
		for (String string : arrs) {
			builder.append(string);
		}
		String temp = Sha1Util.sha1Encode(builder.toString());
		return temp.equals(signature);
	}

	/**
	 * 将微信XML格式数据转换成Map集合
	 * @param ins
	 * @return 结果
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, String> xmlToMap(InputStream ins) throws IOException, DocumentException {
		Map<String, String> map = new HashMap<>(2);
		SAXReader reader = new SAXReader();
		Document document = reader.read(ins);
		Element root = document.getRootElement();
		List<Element> elements = root.elements();
		for (Element element : elements) {
			map.put(StringUtil.toLowerCaseFirstOne(element.getName()), element.getText().trim());
		}
		ins.close();
		return map;
	}

	public static PrintWriter getWriter(HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return writer;
	}

	/**
	 * 打印字符串
	 * @param response
	 * @param msg
	 */
	public static void printlnStr(HttpServletResponse response, String msg) {
		PrintWriter writer = getWriter(response);
		writer.println(msg);
	}

}
